package rabbitmq.workqueues;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import java.io.DataInput;
import java.io.IOException;
import java.util.Date;
import java.util.UUID;
import java.util.concurrent.TimeoutException;
import rabbitmq.common.Const;

/**
 * @author zss
 * @date 2021/8/27 11:35
 * @Email:451682479@qq.com
 */
public class WorkQueueProviderMain {

    private final static String QUEUE_NAME = "work_queue1";
    private final static String VIRTUAL_HOST = "devHost";


    public static void main(String[] args) {

        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost(Const.host);
        factory.setUsername(Const.username);
        factory.setPassword(Const.password);
        factory.setVirtualHost(VIRTUAL_HOST);

        String virtualHost = factory.getVirtualHost();

        System.out.println("virtualHost = " + virtualHost);

        try {
            Connection connection = factory.newConnection();

            Channel channel = connection.createChannel();
            channel.queueDeclare(QUEUE_NAME, false, false, false, null);
            //channel.queueDeclare("job_desc", false, false, false, null);

            /**
             * n order to defeat that we can use the basicQos method with the prefetchCount = 1 setting.
             * This tells RabbitMQ not to give more than one message to a worker at a time. Or,
             * in other words,
             * don't dispatch a new message to a worker until it has processed and acknowledged the previous one.
             * Instead, it will dispatch it to the next worker that is not still busy.
             *
             * https://www.rabbitmq.com/tutorials/tutorial-two-java.html
             */
            channel.basicQos(1);

            for (int i = 0; i < 10000; i++) {
                String message = UUID.randomUUID().toString() + new Date().toString();

                channel.basicPublish("", QUEUE_NAME, null, message.getBytes());
                System.out.println(" [x] Sent '" + message + "'");
                Thread.sleep(500);
            }
        } catch (TimeoutException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

    }

}
